<?php
namespace app\api\controller;

use think\Db;
use org\Qiniu;

class Timing extends Base
{
    public function test(){
        set_time_limit(0);
        $res1='';
        $res2='';
        try{
            $res1 = $this->Jpush(1, '418217', '测试：下单成功', ['n_id' => 1,'type' => 2,'n_type' => 2]);
            $res2 = $this->Jpush(1, '1', '测试：下单成功', ['n_id' => 1,'type' => 2,'n_type' => 2]);
        }catch(\Exception $e){
        }
        dump($res1);
        dump($res2);
        die;
//        $payInfo = [
//            'total_price' => 248,
//            'money' => 248,
//            'number' => '4200001982202311130884215781'
//        ];
//        $tuiwx = new \app\api\controller\Tuiwx();
//        $res = $tuiwx->refundWxUseTranid($payInfo,'tui' . '11130884215781' . '1');
//        dump($res);die;
//
//        $payInfo = [
//            'total_price' => 108,
//            'money' => 108,
//            'number' => '4200002003202311139818356661'
//        ];
//        $tuiwx = new \app\api\controller\Tuiwx();
//        $res = $tuiwx->refundWxUseTranid($payInfo,'tui' . '11139818356661' . '2');
//        dump($res);

//        $res = Db::table('up_self_order')
//            ->where('created_at','>=','2023-11-07 00:01:01')
//            ->where('is_pay','<>',1)
//            ->field('order_no,pay_type')
//            ->select();
//        if($res){
//            foreach ($res as $k => $v){
//                $pay_type = $v['pay_type'];
//                if($pay_type == 1){
//                    $mww_weixinpay =  new \app\api\controller\Weixin();
//                    $a = $mww_weixinpay->chaxunPay($v['order_no']);
//                    dump($a);
//                }elseif($pay_type == 2){
//                    $mww_alipay =  new \app\api\controller\Ali();
//                    $a = $mww_alipay->chaxunPayAli($v['order_no']);
//                    dump($a);
//                }
//            }
//        }
//        dump($res);die;
//        $str = 'AHC016A00,AHC007B00,AHC007C00,AHB004A00,AHA018A00,AHH001A00,AHN001A00,AHB013A00,AHC009A00,AHC017A02,AHC017A03,JSD004A00,JSD001A00,JSD002A00,AHA001A00,AHA004A00,AHA011A00,JSH016A00,JSH013A00,AHD004A02,JSL062A00,JSA137A00,JSA147A00,JSA137A05,JSB001A00,JSH002A00,JSH003A00,JSJ006A00,JSM003A00,JSB007A00,JSB007A04,JSB008A00,JSJ004A00,JSL001A00,JSA024A00,JSL071A00,JSE006A00,JSD008A00,JSA065A02,JSA065A03,JSA065A04,JSA092A00,JSA117A00,JSA120A00,JSA001A00,JSA004A00,JSA003A02,JSA003A03,JSA015A00,JSA068A00,JSA002A00,JSN001A02,JSA006A00,JSA007A00,JSA008A00,JSA009A00,JSA014A00,JSA083A02,JSA215A00,JSA066A00,JSA088A00,JSA119A00,JSA048A00,JSA025A00,JSA026A00,JSA029A02,JSA027A00,JSA121A00,JSA130A00,JSA044A02,JSA044A03,JSA061A00,JSA093A00,JSA122A00,JSA063A00,JSA033A00,JSA031A00,JSA149A00,JSA127A00,JSA089A00,JSA052A00,JSA034C00,JSA219A00,JSA034B02,JSA034A00,JSA038A02,JSA039A00,JSA041A00,JSA032A00,JSA204A00,JSA207A00,JSA210A00,JSA021A00,JSA205A02,JSA205A03,JSA023A00,JSA023A02,JSA209A02,JSA022A00,JSA055A00,JSA103C00,JSA103A00,JSA281A00,JSA103B00,JSA114A00,JSA037A00,JSA080A00,JSA064A00,JSA156A00,JSA212A00,JSA139A00,JSA228A02,JSA228A03,JSA097A00,JSA132A00,JSA126A00,JSA111B00,JSA054A00,JSA054B00,JSA056A00,JSA056A02,JSA056A03,JSA057A00,JSA078A00,JSA018A00,JSF009A00,JSN001B02,JSM002A00,JSM010A00,HBB006A00,HBB005A02,HBB005A03,HBB002A00,HBB001A00,JSB006A00,JSB006A04,JSB004A00,JSB012D00,JSB012B00,JSB012C00,JSB002A00,AHB016A00,AHB001A03,JSJ030A00,ZJA012A00,ZJA010A00,ZJA001A00,ZJA009A00,JSC007A00,JSC012A02,JSC012A03,JSC002A00,JSC005A00,JSC014A00,JSC006A00,JSC028A00,SXJ001A00,JSJ002A00,JSJ009A02,JSJ009A03,JSL004A00,JSL004A03,JSL004A02,JSL021A00,JSL075A00,JSL003A00,JSL030A00,JSL002A00,JSL006A00,JSL020A00,JSA157A00,HNJ001A02,ZJA002A02,AHE003A02,JSA106A02,JSA095A02,JSJ011A02,JSA154A02,JSA108A02,JSA058A02,JSA134A02,JSA128A02,JSA148A02,JSA020A02,JSH015A02,JSA016A02,JSF001A02,JSN004A02,HBB007A02,JSJ029A02,JSL022A02,JSL048A02,JSL040A02,JSL010A02,AHE003A03,JSJ011A03,JSA020A03,JSA019A03,HBB007A03,JSA043A00,JSA110A00,JSA116A00,JSA128A00,JSA019A00,JSH015A04,JSA016A04,JSA016B00,JSA040A00,HBB007A00,JSL005A00,GDM001A00,JSC029A00';
//        $res = Db::table('up_school_good')
//            ->where('sg_school_erp', 'in',$str)
//            ->where('sg_year', 'in','2018,2019,2020')
//            ->setField('sg_status', 2);
//        dump($res);die;
//        $master = [
//            'order_sn' => '202305121544169439658'
//        ];
//        $result = $this->curl_oms('order.detail.get', json_encode($master));
//        dump($result);die;
//        $master = [
//            'order_sn' => '',
//            'deal_code' => '202305121544169439658',
//            'ly_type' => 'openshop'
//        ];
//        $result = $this->curl_oms('order.cancel.delivery', json_encode($master));
//        dump($result);die;
//        $result=json_decode($response,true);
//        if($result['errorCode'] == '000000' && $result['errorMsg'] == '成功'){
//            $res = [
//                'status' => 200,
//                'msg' => $result['result']['paymentUrl']
//            ];
//        }else{
//            $res = [
//                'status' => 100,
//                'msg' => $result['errorMsg']
//            ];
//        }
//        return $res;
    }
	public function yesChangeNo(){
		$res1 = '';
		$res2 = '';
		$no = input('num');
		if(!$no) exit('单号不能为空');
        $tui_id = Db::table('up_self_order_tui')->where('order_erp_wl_no',$no)->column('tui_id');
        $detail_id = Db::table('up_self_order_tui')->where('order_erp_wl_no',$no)->column('order_detail_id');
        if($detail_id){
            $res1 = Db::table('up_self_order_detail')->where('detail_id','in',$detail_id)->setField('refund_status',2);
        }
        if($tui_id){
            $res2 = Db::table('up_self_order_tui')->where('tui_id','in',$tui_id)->update(['status' => 3,'tui_sure_get' => 1]);
        }
        Db::table('up_z_z_copy')->insert([
            'error' => date('Y-m-d H:i:s') . '的售后单号改了拒绝》' . $no
        ]);
		dump($res1);
		dump($res2);
		die;
	}
	public function cancelChangeNo(){
		$res = '';
		$no = input('num');
		if(!$no) exit('单号不能为空');
		$order = Db::table('up_self_order')->where('order_no',$no)->field('order_id,is_send')->find();
		if($order){
			$update = [
				'is_pay' => 1,
				'order_cancel_status' => 2,
				'order_cancel_pay' => 1
			];
			if($order['is_send'] == 0) $update['is_send'] = 1;
			$res = Db::table('up_self_order')->where('order_id',$order['order_id'])->update($update);
		}
		dump($order);
		dump($res);
		die;
	}
    public function xiaobb()
    {
//        $where2 = [];
//        $where2['tui_type'] = 1;
//        $where2['status'] = 2;
//        $where2['erp_push'] = 1;
//        $order_id = Db::table('up_self_order_tui')
//            ->where($where2)
//            ->where('order_erp_wl_no', 'in','app167041159774339985,app167049982586137583,app167059066547472961,app167059113535471453,app167064884849472967,app16707372605269624,app167080726892416306')
//            ->setField('erp_push', 2);
//        dump($order_id);die;
//        $no = 'app166882831521456199,app166883595110463515,app1668990774493963,app166900288722465238,app166911484254450618,app166911724096467342,app166912946258399409,app166924859735377283,app166935074880468515,app166937809481468821,app166938102099464577,app166938254951124351,app166941851665447711,app166945553429195582,app166946065626469170,app166946204810468288,app166947002370424239,app166952954552229015,app166956251515307368,app166956543620468801,app166969511183146125,app166972588124274420,app166972828055469883,app166977334683457558,app166977970264382026,app167004090488471340,app167005698920468681,app167015443398470861,app167019193336283870';
//        $order_id = Db::table('up_self_order_tui')->where('order_erp_wl_no','in',$no)->setField('tui_sure_get',1);
//        dump($order_id);die;
//        $str = 'AHD003A00,AHA023A00,AHA027A00,ZJA003A00,ZJA006A00,JSJ028A00,JSC008A00,JSC016A00,JSC018A00,JSC021A00,JSC022A00,JSC024A00,JSC027A00,JSH019A00,JSB013A00,JSB014A00,JSE012A00,JSE013A00,JSE015A00,JSE017A00,JSD003A00,JSD014A00,JSM023A00,JSL007A00,JSA046A00,JSA050A00,JSA053A00,JSA053A10,JSA053A11,JSA053A12,JSA053B12,JSA053A13,JSA053A14,JSA069A00,JSA069B00,JSA098A00,JSA140A00,JSA145A00,JSA152A00,JSA162A00,JSA168A00,JSA173A00,JSA191A00,JSA192A00,JSA194A00,JSA198A00,JSA203A00';
//        $a = Db::table('up_school_good')->alias('sg')
//            ->join('up_school s','sg.sg_school_erp=s.school_erp','LEFT')
//            ->where('sg_school_erp','not in',$str)
//            ->where('school_type','>',1)
//            ->where('sg_year','in','2014,2015,2016')
//            ->setField('sg_status',2);
//        $a2 = Db::table('up_school_good')->alias('sg')
//            ->join('up_school s','sg.sg_school_erp=s.school_erp','LEFT')
//            ->where('sg_school_erp','not in',$str)
//            ->where('school_type','>',2)
//            ->where('sg_year','in','2017,2018,2019')
//            ->setField('sg_status',2);
//        dump($a);dump($a2);
        die;
//        $res = Db::table('up_self_order')
//            ->where('order_contract',3)
//            ->update([
//                'is_sale' => 1,
//                'order_push_erp' => 3,
//                'admin_tui_push' => 3,
//            ]);
//        $res = Db::table('up_self_order_tui')
//            ->where('tui_type',3)
//            ->update([
//                'erp_push' => 3
//            ]);
//        set_time_limit(0);
//        $page = input('page');
//        $limit = input('limit');
//        $datas = Db::table('up_school_good3')
//            ->page($page,$limit)
//            ->field('sg_id,sg_school_erp,sg_good_coding,sg_year,sg_sex')
//            ->select();
//        $mww = [];
//        if($datas){
//            foreach ($datas as $k => $v){
//                $sgid = $v['sg_id'];
//                unset($v['sg_id']);
////                dump($v);die;
//                $where1 = $v;
//                $where2 = $v;
//                if($v['sg_sex'] == 3){
//                    $where1['sg_sex'] = 1;
//                    $where2['sg_sex'] = 2;
//                    $res = Db::table('up_school_good')
//                        ->where($where1)
//                        ->field('sg_id')
//                        ->find();
//                    if(!$res) $mww[] = $sgid;
//                    $res = Db::table('up_school_good')
//                        ->where($where2)
//                        ->field('sg_id')
//                        ->find();
//                    if(!$res) $mww[] = $sgid;
//                }else{
//                    $res = Db::table('up_school_good')
//                        ->where($v)
//                        ->field('sg_id')
//                        ->find();
//
//                    if(!$res) $mww[] = $sgid;
//                }
//
//            }
//        }
//        if($mww) {
//            $res = Db::table('up_school_good3')->where('sg_id','in',$mww)->setField('good_price',1);
//            Db::table('up_about')->where('id','13')->setInc('phone',count($mww));
//            dump($res);
//        }
//        dump($mww);die;
        //         $db2 = Db::connect('mysql://panson:panson2020app@121.196.57.236:3306/panson#utf8');
//        $res = $db2->table('up_goods')
//            ->where('good_thumb',null)
//            ->field('good_name,good_coding,good_pinming,good_type')
//            ->select();
//        $cellname = [
//            '名字', '款号', '品名', '类型'
//        ];
//        exportExcel('orderinfo',time(),$cellname,$res);
//         $res = $db2->table('up_u_user_son')->alias('sg')
//             ->join('up_school s','sg.uson_school=s.school_id','LEFT')
//             ->field('uson_username,school_name,user_gender,uson_year,uson_grade,uson_class')
//             ->select();
//         $cellname = [
//             '姓名', '学校', '性别', '入学年份', '年级', '班级'
//         ];
//         $status = ['user_gender'];
//         $values = [
//             'user_gender' => [1 => '男',2 => '女']
//         ];
//         exportExcel('order',time(),$cellname,$res,$status,$values);
//        dump($res);
    }

    /**
     * 自营商城的订单相关定时器（1分一跑）
     */
    public function selfshop()
    {
        set_time_limit(0);
        //定时器1：解答超过1小时未提交则清除状态;定时器3：未答题的一小时后关闭
        //1-1：自营订单的超时自动取消
        $today = date('Y-m-d H:i:s');
        $time = time();
        $one_hour_ago = date("Y-m-d H:i:s", ($time - 1800));
        $where['is_pay'] = 0;
        $where['order_contract'] = ['<>', 3];
        $where['o.is_delete'] = 0;
        $where['o.created_at'] = ['<=', $one_hour_ago];
        $field = 'o.order_id,goods_id,num,attr_id,order_contract';
        $res = Db::table('up_self_order')->alias('o')
            ->join('up_self_order_detail od', 'o.order_id=od.order_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->select();
//        dump($res);die;
        if ($res) {
            Db::startTrans();
            try {
                foreach ($res as $k => $v) {
                    if ($v['order_contract'] == 1) {
                        //1、加上商品的库存
                        Db::table('up_self_goods')->where('good_id', $v['goods_id'])->setInc('good_stock', $v['num']);
                        //2、加上attr的库存
                        Db::table('up_self_goods_attr')->where('attr_id', $v['attr_id'])->setInc('stock', $v['num']);
                    }
                    //增补的不用加了
//                    else{
//                        //1、加上商品的库存
//                        Db::table('up_goods')->where('good_id',$v['goods_id'])->setInc('good_stock',$v['num']);
//                        //2、加上attr的库存
//                        Db::table('up_goods')->where('good_id',$v['goods_id'])->setInc("good_{$v['attr_id']}",$v['num']);
//                    }
                }
                //3、改变订单状态
                Db::table('up_self_order o')->where($where)->setField('is_pay', 2);
                Db::commit();
                return 1;
            } catch (\Exception $e) {
                Db::rollback();
                return 2;
            }
        }
    }

    /**
     * 自营商城的订单相关定时器（自动收货和7天售后）
     */
    public function selfshop2()
    {
        set_time_limit(0);
        //定时器1：解答超过1小时未提交则清除状态;定时器3：未答题的一小时后关闭
        //1-1：30天未收货自动收货
        $today = date('Y-m-d H:i:s');
        $time = time();
        $one_hour_ago = date("Y-m-d H:i:s", ($time - 3600 * 24 * 24));
        $where['is_pay'] = 1;
        $where['is_send'] = 1;
//        $where['order_contract'] = ['<>', 3];
        $where['is_delete'] = 0;
        $where['send_time'] = ['<=', $one_hour_ago];
        Db::table('up_self_order')
            ->where($where)
            ->update([
                'is_send' => 2,
                'confirm_time' => $today
            ]);
        //1-1：超过7天未售后则不能再申请
        $one_hour_ago = date("Y-m-d H:i:s", ($time - 3600 * 24 * 7));
        unset($where['send_time']);
        $where['is_send'] = ['>=', 2];
        $where['is_sale'] = 0;
        $where['confirm_time'] = ['<=', $one_hour_ago];
        Db::table('up_self_order')->where($where)->setField('is_sale', 1);
        return 1;
    }

    /**
     * 8小时之后再推送给erp
     */
    public function erpZengbuHours()
    {
        
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $hours = Db::table('up_about')->where('id', 9)->value('content');
//        $hours = (int)$hours;
        $hours_ago = date("Y-m-d H:i:s", ($time - 3600 * $hours));
        $where['is_pay'] = 1;
        $where['order_contract'] = 2;
        $where['o.is_delete'] = 0;
        $where['o.is_send'] = 0;
        $where['o.order_push_erp'] = 1;
        $where['o.order_cancel_status'] = ['<=', 2];
        $where['o.pay_time'] = ['<=', $hours_ago];
        $field = 'o.order_no,o.order_id,o.name,o.mobile,o.address,o.order_address2,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',o.order_erp_year,o.order_erp_done,o.order_back_order_id,o.created_at,o.remark,o.pay_type';
        $ids = '15923920265889501,15923965045850273,15923967655731051';
        $ids .= ',15923967957642564,15923968251398936';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where)
            ->field($field)
            ->page(1,50)
            ->select();
//        dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['order_no'],
//                    'iSaleType' => 2, //1统购  2增补
                    'iBusiness' => 1, //1 是增补，2是换货的增补
                    'dOrderMoney' => $v['all_goods_price'],
                    'dFreight' => $v['express_original_price'],
                    'cReceiveName' => $v['name'],
                    'cReceiveMobile' => $v['mobile'],
                    'cReceiveAddress' => $v['order_address2'],
//                    'cStuName' => $v['uson_username'] ?: '',
//                    'cStuID' => $v['uson_idcard'] ?: '',
//                    'cStuMobile' => $v['uson_parent_phone'] ?: '',
                    'cStuSchool' => $v['school_erp'] ?: '',
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cHPreDate' => $v['order_erp_done'] ? date('Y-m-d',strtotime($v['order_erp_done'])) : '',
                    'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                    'cStuGrade' => $v['uson_grade'] ?: '',
                    'cStuClass' => $v['uson_class'] ?: '',
                    'iYears' => $v['order_erp_year'],
//                    'cPreDate' => $v['order_erp_done'],
                    'cSerialNum' => $v['order_back_order_id'],
                    'Oldordercode' => '',
                    'cRemark' => $v['remark'],
                    'cDate' => substr($v['created_at'], 0, 10)
                ];
                $field = 'goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,unit_price dPrice,num dQty,s.user_gender iSex';
                $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field($field)
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_no'] . $v['order_id']
                ];
                $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->update(['order_push_erp' => 2,'new_erp_have' => 2]);
                }else{
                    dump($result);
                }
            }
        }
    }
    /**
     * 8小时之后再推送给erp
     */
    public function erpZengbuHours2()
    {
        
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $hours = Db::table('up_about')->where('id', 14)->value('content');
//        $hours = (int)$hours;
        $hours_ago = date("Y-m-d H:i:s", ($time - 3600 * $hours));
        $where['is_pay'] = 1;
        $where['order_contract'] = 3;
        $where['o.is_delete'] = 0;
        $where['o.is_send'] = 0;
        $where['o.order_push_erp'] = 1;
        $where['o.pay_time'] = ['<=', $hours_ago];
        $field = 'o.order_no,o.order_id,o.name,o.mobile,o.address,o.order_address2,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',o.order_erp_year,o.order_erp_done,o.order_back_order_id,o.created_at,o.remark,o.pay_type';
        $ids = '15923920265889501,15923965045850273,15923967655731051';
        $ids .= ',15923967957642564,15923968251398936';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where)
            ->field($field)
            ->page(1,50)
            ->select();
        //dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['order_no'],
//                    'iSaleType' => 2, //1统购  2增补
                    'iBusiness' => 3, //1 是增补，2是换货的增补 3 4
                    'dOrderMoney' => $v['all_goods_price'],
                    'dFreight' => $v['express_original_price'],
                    'cReceiveName' => $v['name'],
                    'cReceiveMobile' => $v['mobile'],
                    'cReceiveAddress' => $v['order_address2'],
//                    'cStuName' => $v['uson_username'] ?: '',
//                    'cStuID' => $v['uson_idcard'] ?: '',
//                    'cStuMobile' => $v['uson_parent_phone'] ?: '',
                    'cStuSchool' => $v['school_erp'] ?: '',
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cHPreDate' => $v['order_erp_done'] ? date('Y-m-d',strtotime($v['order_erp_done'])) : '',
                    'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                    'cStuGrade' => $v['uson_grade'] ?: '',
                    'cStuClass' => $v['uson_class'] ?: '',
                    'iYears' => $v['order_erp_year'],
//                    'cPreDate' => $v['order_erp_done'],
                    'cSerialNum' => $v['order_back_order_id'],
                    'Oldordercode' => '',
                    'cRemark' => $v['remark'],
                    'cDate' => substr($v['created_at'], 0, 10)
                ];
                $field = 'goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,unit_price dPrice,num dQty,s.user_gender iSex';
                $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                $field .= ',tsl_number cU8SoCode,tg_tsl_id';
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->join('up_tg_school_list tsl', 'od.tg_tsl_id=tsl.tsl_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field($field)
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_no'] . $v['order_id']
                ];
//                dump($body);die;
                $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
//                dump($result);die;
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->update(['order_push_erp' => 2,'new_erp_have' => 2]);
                }else{
                    dump($result);
                }
            }
        }
    }

    /**
     * 8小时之后再推送给erp
     */
    public function erpZengbuHoursForError()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $hours = Db::table('up_about')->where('id', 9)->value('content');
//        $hours = (int)$hours;
        $hours_ago = date("Y-m-d H:i:s", ($time - 3600 * $hours));
        $where['is_pay'] = 1;
        $where['order_contract'] = 2;
        $where['o.is_delete'] = 0;
        $where['o.is_send'] = 0;
        $where['o.order_push_erp'] = 1;
        $where['o.order_cancel_status'] = ['<=', 2];
        //$where['o.pay_time'] = ['<=', $hours_ago];
        $field = 'o.order_no,o.order_id,o.name,o.mobile,o.address,o.order_address2,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',o.order_erp_year,o.order_erp_done,o.order_back_order_id,o.created_at,o.remark,o.pay_type';
        $ids = '15923920265889501,15923965045850273,15923967655731051';
        $ids .= ',15923967957642564,15923968251398936';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where)
            ->where('order_no','202306071419381485269')
            ->field($field)
            ->page(1,50)
            ->select();
       dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['order_no'],
//                    'iSaleType' => 2, //1统购  2增补
                    'iBusiness' => 1, //1 是增补，2是换货的增补
                    'dOrderMoney' => $v['all_goods_price'],
                    'dFreight' => $v['express_original_price'],
                    'cReceiveName' => $v['name'],
                    'cReceiveMobile' => $v['mobile'],
                    'cReceiveAddress' => $v['order_address2'],
//                    'cStuName' => $v['uson_username'] ?: '',
//                    'cStuID' => $v['uson_idcard'] ?: '',
//                    'cStuMobile' => $v['uson_parent_phone'] ?: '',
                    'cStuSchool' => $v['school_erp'] ?: '',
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cHPreDate' => $v['order_erp_done'] ? date('Y-m-d',strtotime($v['order_erp_done'])) : '',
                    'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                    'cStuGrade' => $v['uson_grade'] ?: '',
                    'cStuClass' => $v['uson_class'] ?: '',
                    'iYears' => $v['order_erp_year'],
//                    'cPreDate' => $v['order_erp_done'],
                    'cSerialNum' => $v['order_back_order_id'],
                    'Oldordercode' => '',
                    'cRemark' => $v['remark'],
                    'cDate' => substr($v['created_at'], 0, 10)
                ];
                $field = 'goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,unit_price dPrice,num dQty,s.user_gender iSex';
                $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field($field)
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_no'] . $v['order_id']
                ];
                $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->update(['order_push_erp' => 2,'new_erp_have' => 2]);
                }else{
                    dump($result);
                }
            }
        }
    }

    /**
     * 同步物流信息
     */
    public function getWuliu()
    {
        extract(input());
        //模拟erp返回物流信息时改订单状态
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $return = [
            'errcode' => 0,
            'errmsg' => '',
            'id' => '',
            'code' => '',
            'tradeid' => '',
            'data' => '',
        ];
        if(!isset($logisticsList) || !$logisticsList){
            $return['errcode'] = 404;
            $return['errmsg'] = '没拿到参';
            return json($return);
        }
//        Db::table('up_zzzz_zerp')
//            ->insert([
//                'content' => json_encode($logisticsList)
//            ]);

//        $datas = json_decode(json_encode($logisticsList), true);
//        if(is_array($datas)){
//            $return['errcode'] = -1;
//            $return['errmsg'] = '';
//            return json($return);
//        }else{
//            $return['errcode'] = -2;
//            $return['errmsg'] = '';
//            return json($return);
//        }
        $datas = json_decode(json_encode($logisticsList), true);
//        $datas = json_decode($logisticsList, true);
        if (is_array($datas)) {
            Db::startTrans();
            try {
                foreach ($datas as $k => $v) {
                    $SOURTYPE = $v['SOURTYPE'];
                    $APP_DOCNO = $v['APP_DOCNO'];
                    $COMNAME = $v['COMNAME'];
                    if($COMNAME == 'JDKD') $COMNAME = '京东快递';
                    $FASTNO = $v['FASTNO'];
                    $UNIQUE_NUMBER = $v['UNIQUE_NUMBER'];
                    $mwwLessFour = substr($UNIQUE_NUMBER,4,-1); // 第四位有可能会有变化，从第五位开始
                    $CWHCODE = $v['CWHCODE'];
                    if ($SOURTYPE == 1) { //1 是增补，2是换货的增补
                        $order = Db::table('up_self_order')->where('order_no', $APP_DOCNO)->field('order_id,is_send')->find();
                        $is_send = $order['is_send'];
                        if ($is_send == 0 || $is_send == 1) {
                            Db::table('up_self_order')
                                ->where('order_no', $APP_DOCNO)
                                ->update([
                                    'is_send' => 1,
                                    'send_time' => $today,
                                    'updated_at' => $today,
                                    'express' => $COMNAME,
                                    'express_no' => $FASTNO,
                                ]);
                        }
                        Db::table('up_self_order_detail')
                            ->where('order_id', $order['order_id'])
                            ->where('goods_coding_unique', 'like','%'.$mwwLessFour.'%')
                            ->update([
                                'updated_at' => $today,
                                'detail_express' => $COMNAME,
                                'detail_express_no' => $FASTNO,
                                'store_code' => $CWHCODE,
                            ]);
                    } else if($SOURTYPE == 2){
                        $order_id = Db::table('up_self_order_tui')
                            ->where('order_erp_wl_no', $APP_DOCNO)
                            ->value('order_id');
                        if ($order_id) {
                            $res = Db::table('up_self_order_tui')
                                ->where('order_erp_wl_no', $APP_DOCNO)
                                ->where('erp_huan_uninumber', 'like','%'.$mwwLessFour.'%')
                                ->where('status', 2)
                                ->update([
                                    'is_send' => 1,
                                    'send_time' => $today,
                                    'updated_at' => $today,
                                    'merchant_express' => $COMNAME,
                                    'merchant_express_no' => $FASTNO,
                                ]);
                            $jj_deids = Db::table('up_self_order_tui')
                                ->where('order_erp_wl_no', $APP_DOCNO)
                                ->where('erp_huan_uninumber', 'like','%'.$mwwLessFour.'%')
                                ->where('status', 2)
                                ->column('order_detail_id');
                            Db::table('up_self_order_detail')
                                ->where('detail_id', 'in', $jj_deids)
                                ->setField('refund_status', 2);

                            $sale_status = Db::table('up_self_order')
                                ->where('order_id', $order_id)
                                ->value('sale_status');
                            if ($sale_status != 0) {
                                Db::table('up_self_order')
                                    ->where('order_id', $order_id)
                                    ->setField('tui_status', 1);
                            }
                        }
                    }else if($SOURTYPE == 3){
                        $order = Db::table('up_self_order')->where('order_no', $APP_DOCNO)->field('order_id,is_send')->find();
                        $is_send = $order['is_send'];
                        if ($is_send == 0) {
                            Db::table('up_self_order')
                                ->where('order_no', $APP_DOCNO)
                                ->update([
                                    'is_send' => 1,
                                    'send_time' => $today,
                                    'updated_at' => $today
                                ]);
                        }
                        $UNIQUE_NUMBER = substr($UNIQUE_NUMBER,0,13);
                        Db::table('up_self_order_detail')
                            ->where('order_id', $order['order_id'])
                            ->where('goods_coding_unique', 'like','%' . $UNIQUE_NUMBER . '%')
                            ->update([
                                'updated_at' => $today,
                                'detail_express' => $COMNAME,
                                'detail_express_no' => $FASTNO,
                            ]);
                    }else if($SOURTYPE == 4){
                        $order_id = Db::table('up_self_order_tui')
                            ->where('order_erp_wl_no', $APP_DOCNO)
                            ->value('order_id');
                        $UNIQUE_NUMBER = substr($UNIQUE_NUMBER,0,13);
                        if ($order_id) {
                            $res = Db::table('up_self_order_tui')
                                ->where('order_erp_wl_no', $APP_DOCNO)
                                ->where('erp_huan_uninumber', 'like','%' . $UNIQUE_NUMBER . '%')
                                ->where('status', 2)
                                ->update([
                                    'is_send' => 1,
                                    'send_time' => $today,
                                    'updated_at' => $today,
                                    'merchant_express' => $COMNAME,
                                    'merchant_express_no' => $FASTNO,
                                ]);
                            $jj_deid = Db::table('up_self_order_tui')
                                ->where('order_erp_wl_no', $APP_DOCNO)
                                ->where('status', 2)
                                ->where('erp_huan_uninumber', 'like','%' . $UNIQUE_NUMBER . '%')
                                ->value('order_detail_id');
                            Db::table('up_self_order_detail')
                                ->where('detail_id', $jj_deid)
                                ->setField('refund_status', 2);
                            $sale_status = Db::table('up_self_order')
                                ->where('order_id', $order_id)
                                ->value('sale_status');
                            if ($sale_status != 0 && $sale_status != 1) {
                                Db::table('up_self_order')
                                    ->where('order_id', $order_id)
                                    ->setField('tui_status', 1);
                            }
                        }
                    }
                }
                Db::commit();
                return json($return);
            } catch (\Exception $e) {
                Db::rollback();
                $return['errcode'] = -1;
                $return['errmsg'] = '';
                return json($return);
            }

        }else{
            Db::table('up_zzzz_zerp')
                ->insert([
                    'content' => json_encode($logisticsList)
                ]);
            $return['errcode'] = -2;
            $return['errmsg'] = '';
            return json($return);
        }
    }

    /**
     * 未发货之前取消订单的，发给erp
     */
    public function cancelOrderErp()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $where = [];
        $where['is_pay'] = 2;
        $where['order_contract'] = 2;
        $where['o.is_delete'] = 0;
        $where['o.order_push_erp'] = 2; //没推过的不用
        $where['o.order_cancel_push_erp'] = 1;
        $where['o.order_cancel_status'] = 3;
        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',order_cancel_number,order_cancel_time,order_cancel_remark,new_erp_have';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where)
            ->field($field)
            ->select();
//        dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['order_cancel_number'],
                    'cOrgOrderNo' => $v['order_no'],
                    'cDate' => substr($v['order_cancel_time'], 0, 10),
                    'iType' => 2, //2是增补还未发货就取消了订单  4是收货完成以后退货
                    'dTotRetamt' => $v['all_goods_price'] + $v['express_original_price'],
                    'cStuName' => $v['uson_username'],
                    'cStuID' => $v['uson_idcard'],
                    'cStuMobile' => $v['uson_parent_phone'],
                    'cStuSchool' => $v['school_erp'],
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cStuGrade' => $v['uson_grade'],
                    'cStuClass' => $v['uson_class'],
                    'cRemark' => $v['order_cancel_remark'],
                    'isInit' => $v['new_erp_have'] % 2,
                ];
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field('goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,num dQty,CAST(s.user_gender AS CHAR) iSex')
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_cancel_number'] . $v['order_id']
                ];
                $url = config('erpoms')['erpurl'] . "/Api/App/RefundOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
//                    dump($result);die;
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->setField('order_cancel_push_erp', 2);
                }else{
                    dump($result);
                }
            }
        }
        //2、售后的推不管退还是换，先推个售后
        $where2 = [];
        $where2['tui_type'] = 2;
        $where2['status'] = 2;
        $where2['erp_push'] = 1;
        $where2['t.express_no'] = ['<>',''];

        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,o.name,o.mobile,o.address,o.order_address2,o.order_back_order_id';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',t.type,t.order_erp_wl_no,o.pay_type';
        $field .= ',t.erp_year,t.erp_done,t.express,t.express_no,t.remark,t.created_at,t.status_time,new_erp_have';

        $datas = Db::table('up_self_order_tui')->alias('t')
            ->join('up_self_order o', 't.order_id=o.order_id', 'LEFT')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where2)
//            ->where('order_erp_wl_no','in','app168534544759393018')
            ->field($field)
            ->group('order_erp_wl_no')
            ->select();
       //dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                //A:先推退货
                $youhua_status = false;
                $master = [
                    'cAppOrderNo' => $v['order_erp_wl_no'] . 'T', //防止跟下面的新单重复单号
                    'cOrgOrderNo' => $v['order_no'],
                    'iType' => $v['type'] + 2, //2是增补还未发货就取消了订单  3是收货完成以后换货  4是收货完成以后退货
                    'dTotRetamt' => $v['all_goods_price'],
                    'cStuName' => $v['uson_username'],
                    'cStuID' => $v['uson_idcard'],
                    'cStuMobile' => $v['uson_parent_phone'],
                    'cStuSchool' => $v['school_erp'],
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cStuGrade' => $v['uson_grade'],
                    'cStuClass' => $v['uson_class'],
                    'cComName' => $v['express'],
                    'cFastNo' => $v['express_no'],
                    'cRemark' => $v['remark'],
                    'cDate' => $today, //$v['status_time'],
                    'isInit' => $v['new_erp_have'] % 2,
                ];
                //->field('od.goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,refund_num dQty,CAST(s.user_gender AS CHAR) iSex')
                $details = Db::table('up_self_order_tui')->alias('t')
                    ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where($where2)
                    ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                    ->field('od.detail_id cUniqueNumber,good_coding cProCode,attr_id cProSize,od.num dQty,CAST(s.user_gender AS CHAR) iSex')
                    ->select();
                foreach ($details as $k222 => $v222){
                    $oldSD = $this->getLastInfo($v222['cUniqueNumber'],$v['type']);
                    $details[$k222]['cUniqueNumber'] = $oldSD['erp_huan_uninumber'];
                    $details[$k222]['cProSize'] = $oldSD['erp_old_size'];
                    if($v['type'] == 2) $details[$k222]['cProSize'] = $oldSD['erp_new_size'];
                    if($details[$k222]['cProSize'] == '0' || $details[$k222]['cProSize'] == '000') $details[$k222]['cProSize'] = '均码';
                }
                if(isset($oldSD['order_erp_wl_no']) && $oldSD['order_erp_wl_no']){
                    $master['cOrgOrderNo'] = $oldSD['order_erp_wl_no']; // 确保单号正确
                }
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_erp_wl_no'] . $v['order_id'] . 'T'
                ];
//                dump($body);die;
                $url = config('erpoms')['erpurl'] . "/Api/App/RefundOrderSync";
                $result = $this->curl_erp($url, json_encode($body));//dump($result);die;
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    $youhua_status = true;
                    Db::table('up_self_order_tui')->alias('t')
                        ->where($where2)
                        ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                        ->setField('erp_push', 2);
                }else{
                    dump($result);
                }
                //B:换货的再推增补单
//                if ($v['type'] == 1 && $youhua_status == true) {
//                    $master = [
//                        'cAppOrderNo' => $v['order_erp_wl_no'],
//                        'iBusiness' => 2, //1 是增补，2是换货的增补
//                        'dOrderMoney' => $v['all_goods_price'],
//                        'dFreight' => $v['express_original_price'],
//                        'cReceiveName' => $v['name'],
//                        'cReceiveMobile' => $v['mobile'],
//                        'cReceiveAddress' => $v['order_address2'],
////                            'STU_NAME' => $v['uson_username'],
////                            'STU_ID' => $v['uson_idcard'],
////                            'STU_PHONE' => $v['uson_parent_phone'],
//                        'cStuSchool' => $v['school_erp'],
//                        'cSchoolName' => $v['school_name'] ?: '',
//                        'cHPreDate' => date('Y-m-d',time()+3600*24*10),
//                        'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
//                        'cStuGrade' => $v['uson_grade'],
//                        'cStuClass' => $v['uson_class'],
//                        'iYears' => $v['erp_year'],
////                            'PREDATE' => $v['erp_done'],
//                        'cSerialNum' => $v['order_back_order_id'],
//                        'cOldOrderCode' => $v['order_no'],
//                        'cDate' => $today,
//                        'cRemark' => '',
//                    ];
////                    'erp_huan_uninumber cUniqueNumber,good_coding cProCode,erp_new_size cProSize,unit_price dPrice,refund_num dQty,s.user_gender iSex';
//                    $field = 'erp_huan_uninumber cUniqueNumber,good_coding cProCode,erp_new_size cProSize,unit_price dPrice,od.num dQty,s.user_gender iSex';
//                    $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
//                    $details = Db::table('up_self_order_tui')->alias('t')
//                        ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
//                        ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
//                        ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
//                        ->where($where2)
//                        ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
//                        ->field($field)
//                        ->select();
//                    $body = [
//                        'Head' => $master,
//                        'Rows' => $details,
//                        'Tradeid' => $v['order_erp_wl_no'] . $v['order_id']
//                    ];
//					// dump($body);die;
//                    $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderSync";
////                    $url = "http://36.152.23.203:4941/Api/App/SaleOrderSync";
//                    $result = $this->curl_erp($url, json_encode($body));
//                    if (isset($result['errcode']) && $result['errcode'] == 0) {
//                        Db::table('up_self_order_tui')
//                            ->where($where2)
//                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
//                            ->setField('erp_push', 2);
//                    }else{
//                        dump($result);
//                    }
//                } else {
//                    if ($youhua_status == true) {
//                        Db::table('up_self_order_tui')
//                            ->where($where2)
//                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
//                            ->setField('erp_push', 2);
//                    }
//                }
            }

        }
		exit();

    }
    /**
     * 申请售后，用户回寄，然后u8告诉我是不是收到货了，收到了就推给u8一个增补单
     */
    public function receiveSaleExpress()
    {

        set_time_limit(0);
        $cAppOrderNo = input('refNo');
        $return = [
            'errcode' => 0,
            'errmsg' => '',
            'id' => '',
            'code' => '',
            'tradeid' => '',
            'data' => '',
        ];
        $today = date('Y-m-d H:i:s');
        $time = time();
        $order_erp_wl_no = substr($cAppOrderNo,0,-1);

        $field = 'o.order_no,o.order_id,o.user_id,o.order_contract,o.total_price,all_goods_price,express_original_price,o.name,o.mobile,o.address,o.order_address2,o.order_back_order_id';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',t.type,t.tui_id,t.order_erp_wl_no,o.pay_type';
        $field .= ',t.erp_year,t.tui_sure_get,t.erp_done,t.express,t.express_no,t.remark,t.created_at,t.status_time,new_erp_have';

        $v = Db::table('up_self_order_tui')->alias('t')
            ->join('up_self_order o', 't.order_id=o.order_id', 'LEFT')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where('order_erp_wl_no',$order_erp_wl_no)
            ->where('tui_sure_get',1) //如果是明细推的，那第一条之后就不用再推了
            ->field($field)
            ->find();
//        dump($v);die;
        if ($v) {
            if ($v['type'] == 1 && $v['status_time'] >= '2023-06-06 14:10:00') {
                $master = [
                    'cAppOrderNo' => $v['order_erp_wl_no'],
                    'iBusiness' => 2, //1 是增补，2是换货的增补
                    'dOrderMoney' => $v['all_goods_price'],
                    'dFreight' => $v['express_original_price'],
                    'cReceiveName' => $v['name'],
                    'cReceiveMobile' => $v['mobile'],
                    'cReceiveAddress' => $v['order_address2'],
//                            'STU_NAME' => $v['uson_username'],
//                            'STU_ID' => $v['uson_idcard'],
//                            'STU_PHONE' => $v['uson_parent_phone'],
                    'cStuSchool' => $v['school_erp'],
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cHPreDate' => date('Y-m-d',time()+3600*24*10),
                    'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                    'cStuGrade' => $v['uson_grade'],
                    'cStuClass' => $v['uson_class'],
                    'iYears' => $v['erp_year'],
//                            'PREDATE' => $v['erp_done'],
                    'cSerialNum' => $v['order_back_order_id'],
                    'cOldOrderCode' => $v['order_no'],
                    'cDate' => $today,
                    'cRemark' => '',
                ];
//                    'erp_huan_uninumber cUniqueNumber,good_coding cProCode,erp_new_size cProSize,unit_price dPrice,refund_num dQty,s.user_gender iSex';
                $field = 'erp_huan_uninumber cUniqueNumber,good_coding cProCode,erp_new_size cProSize,unit_price dPrice,od.num dQty,s.user_gender iSex';
                $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                $details = Db::table('up_self_order_tui')->alias('t')
                    ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                    ->field($field)
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_erp_wl_no'] . $v['order_id']
                ];
                // dump($body);die;
                $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    //只改确认收到货的状态即可，此时只要接收到就推给U8，如果单独跑定时器，比如抓取已收到的同意的，那之前的也会推过去
                    Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                        ->setField('tui_sure_get', 2);
                }else{
                    $return['errcode'] = -1;
                    $return['errmsg'] = '';
//                    dump($result);
                }
            }else{
                $res = Db::table('up_self_order_tui')
                    ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                    ->setField('tui_sure_get', 2);
                if($res){
                    //直接退款给用户
                    $auto = Db::table('up_about')->where('id',20)->value('content');
                    if($auto == 1){
                        $should_money = Db::table('up_self_order_tui')
                            ->where('order_erp_wl_no',$order_erp_wl_no)
                            ->where('status',2)
                            ->where('is_send',0)
                            ->sum('should_money');
                        if($should_money > 0 && $should_money <= $v['all_goods_price']){
                            $update  = [
                                'is_send' => 1,
                                'tui_master_status' => 4,
                                'refund_price' => $should_money,
                                'send_time' => $today,
                                'updated_at' => $today,
                            ];
                            $payInfo = [
                                'total_price' => $v['total_price'],
                                'money' => $should_money,
                                'number' => $v['order_no']
                            ];
                            if($v['pay_type'] == 1){ //微信
                                $tuiwx = new \app\api\controller\Tuiwx();
                                $res = $tuiwx->refundWx($payInfo,$order_erp_wl_no);
                            }elseif ($v['pay_type'] == 2){ //支付宝
                                $tuiali = new \app\api\controller\Ali();
                                $res = $tuiali->refund($payInfo,$order_erp_wl_no);
                            }else{
                                //支付方式有问题？不会出现这个情况
                                $update = [
                                    'merchant_remark' => 'mww-查找无此支付方式'
                                ];
                            }
                            if($res['status'] != 200) {
                                $update = [
                                    'merchant_remark' => 'mww-退款失败' . $res['msg']
                                ];
                            }
                            Db::table('up_self_order_tui')
                                ->where('order_erp_wl_no',$order_erp_wl_no)
                                ->where('status',2)
                                ->where('is_send',0)
                                ->update($update);
                            if($res['status'] == 200) {
                                $jj_deids = Db::table('up_self_order_tui')
                                    ->where('order_erp_wl_no',$order_erp_wl_no)
                                    ->where('status',2)
                                    ->where('is_send',0)
                                    ->column('order_detail_id');
                                Db::table('up_self_order_detail')
                                    ->where('detail_id', 'in',$jj_deids)
                                    ->setField('refund_status',2);
                                $order_id = $v['order_id'];
                                $sale_status = Db::table('up_self_order')
                                    ->where('order_id', $order_id)
                                    ->value('sale_status');
                                if($sale_status != 0){
                                    Db::table('up_self_order')
                                        ->where('order_id', $order_id)
                                        ->setField('tui_status',1);
                                }
                                allInRevenue(2,$should_money,$v['user_id'],$v['order_contract'],$v['order_id'],'自动退款',$v['tui_id']);
                            }
                        }
                    }
                }
            }
        }else{
//            $return['errcode'] = 404;
            $return['errmsg'] = '查无此单';
        }
        return json($return);
    }
    /**
     * 未发货之前取消订单的，发给erp
     */
    public function cancelOrderErp2()
    {

        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        //1、先处理整单退货的
        $where = [];
        $where['is_pay'] = 1;
        $where['order_contract'] = 3;
        $where['o.is_delete'] = 0;
        $where['o.order_push_erp'] = 2; //没推过的不用
        $where['o.admin_tui'] = 3;
        $where['o.admin_tui_push'] = 1;
        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',admin_tui_number,admin_tui_addtime,order_cancel_remark,new_erp_have';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where)
            ->field($field)
            ->select();
//        dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['admin_tui_number'],
                    'cOrgOrderNo' => $v['order_no'],
                    'cDate' => substr($v['admin_tui_addtime'], 0, 10),
                    'iType' => 6, //2是增补还未发货就取消了订单  4是收货完成以后退货 5大货换  6大货退
                    'dTotRetamt' => $v['all_goods_price'] + $v['express_original_price'],
                    'cStuName' => $v['uson_username'],
                    'cStuID' => $v['uson_idcard'],
                    'cStuMobile' => $v['uson_parent_phone'],
                    'cStuSchool' => $v['school_erp'],
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cStuGrade' => $v['uson_grade'],
                    'cStuClass' => $v['uson_class'],
                    'cRemark' => '',
                    'isInit' => $v['new_erp_have'] % 2,
                ];
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field('goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,num dQty,CAST(s.user_gender AS CHAR) iSex')
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['admin_tui_number'] . $v['order_id']
                ];
                $url = config('erpoms')['erpurl'] . "/Api/App/RefundOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
//                    dump($result);die;
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->setField('admin_tui_push', 2);
                }else{
                    dump($result);
                }
            }
        }
        //2、售后的先推个售后(不会有退货)
        $where2 = [];
        $where2['tui_type'] = 3;
        $where2['status'] = 2;
        $where2['tui_sure_get'] = 2;
        $where2['erp_push'] = 1;

        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,o.name,o.mobile,o.address,o.order_address2,o.order_back_order_id';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',t.type,t.order_erp_wl_no,o.pay_type';
        $field .= ',t.erp_year,t.erp_done,t.express,t.express_no,t.remark,t.created_at,t.status_time,new_erp_have';

        $datas = Db::table('up_self_order_tui')->alias('t')
            ->join('up_self_order o', 't.order_id=o.order_id', 'LEFT')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where2)
//            ->where('order_erp_wl_no','in','app1592399658627701,app1592400067811015')
            ->field($field)
            ->group('order_erp_wl_no')
//            ->page(1,1)
            ->select();
//        dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                //A:先推退货
                $youhua_status = false;
                $master = [
                    'cAppOrderNo' => $v['order_erp_wl_no'] . 'T', //防止跟下面的新单重复单号
                    'cOrgOrderNo' => $v['order_no'],
                    'iType' => 5, //2是增补还未发货就取消了订单  3是收货完成以后换货  4是收货完成以后退货  5大货换  6大货退（56和34）
                    'dTotRetamt' => $v['all_goods_price'],
                    'cStuName' => $v['uson_username'],
                    'cStuID' => $v['uson_idcard'],
                    'cStuMobile' => $v['uson_parent_phone'],
                    'cStuSchool' => $v['school_erp'],
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cStuGrade' => $v['uson_grade'],
                    'cStuClass' => $v['uson_class'],
                    'cComName' => $v['express'],
                    'cFastNo' => $v['express_no'],
                    'cRemark' => $v['remark'],
                    'cDate' => $v['status_time'],
                    'isInit' => $v['new_erp_have'] % 2,
                ];
                $details = Db::table('up_self_order_tui')->alias('t')
                    ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where($where2)
                    ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                    ->field('od.goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,refund_num dQty,CAST(s.user_gender AS CHAR) iSex')
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_erp_wl_no'] . $v['order_id'] . 'T'
                ];
//                dump($body);die;
                $url = config('erpoms')['erpurl'] . "/Api/App/RefundOrderSync";
                $result = $this->curl_erp($url, json_encode($body));//dump($result);die;
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    $youhua_status = true;
                }else{
                    dump($result);
                }
                //B:换货的再推增补单
                if ($v['type'] == 1 && $youhua_status == true) {
                    $master = [
                        'cAppOrderNo' => $v['order_erp_wl_no'],
                        'iBusiness' => 4, //1 是增补，2是换货的增补
                        'dOrderMoney' => $v['all_goods_price'],
                        'dFreight' => $v['express_original_price'],
                        'cReceiveName' => $v['name'],
                        'cReceiveMobile' => $v['mobile'],
                        'cReceiveAddress' => $v['order_address2'],
//                            'STU_NAME' => $v['uson_username'],
//                            'STU_ID' => $v['uson_idcard'],
//                            'STU_PHONE' => $v['uson_parent_phone'],
                        'cStuSchool' => $v['school_erp'],
                        'cSchoolName' => $v['school_name'] ?: '',
                        'cHPreDate' => date('Y-m-d',time()+3600*24*10),
                        'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                        'cStuGrade' => $v['uson_grade'],
                        'cStuClass' => $v['uson_class'],
                        'iYears' => $v['erp_year'],
//                            'PREDATE' => $v['erp_done'],
                        'cSerialNum' => $v['order_back_order_id'],
                        'cOldOrderCode' => $v['order_no'],
                        'cDate' => $today,
                        'cRemark' => '',
                    ];
                    $field = 'erp_huan_uninumber cUniqueNumber,good_coding cProCode,erp_new_size cProSize,unit_price dPrice,refund_num dQty,s.user_gender iSex';
                    $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                    $details = Db::table('up_self_order_tui')->alias('t')
                        ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                        ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                        ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                        ->where($where2)
                        ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                        ->field($field)
                        ->select();
                    $body = [
                        'Head' => $master,
                        'Rows' => $details,
                        'Tradeid' => $v['order_erp_wl_no'] . $v['order_id']
                    ];
//					 dump($body);die;
                    $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderSync";
                    $result = $this->curl_erp($url, json_encode($body));
                    if (isset($result['errcode']) && $result['errcode'] == 0) {
                        Db::table('up_self_order_tui')
                            ->where($where2)
                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                            ->setField('erp_push', 2);
                    }else{
                        dump($result);
                    }
                } else {
                    if ($youhua_status == true) {
                        Db::table('up_self_order_tui')
                            ->where($where2)
                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                            ->setField('erp_push', 2);
                    }
                }
            }
        }
    }


    public function dowload()
    {//echo 1;die;
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
            echo "<script> location.href='https://itunes.apple.com/cn/app/id1516439349'; </script>";
        } else {
            echo "<script> location.href='https://a.app.qq.com/o/simple.jsp?pkgname=com.paixun.fz'; </script>";
        }

    }

    /**
     * 获取引导页
     * @return \think\response\Json
     */
    public function getYinDao()
    {
        $lunbo = Db::table('up_appstart')
            ->where('banner_status', 1)
            ->field('banner_img as url')
            ->order('banner_sort ASC')
            ->page(1, 5)
            ->select();
        return json(['status' => 200, 'msg' => $lunbo]);
    }

    /**
     * 同步老用户
     */
    public function oldGoNew()
    {
//        set_time_limit(0);
//        $db2 = Db::connect('mysql://root:5b5u8419,.@221.231.139.177:3306/new#utf8');
//        $subQuery  = $db2->table("app_register_info")
//            ->where('update_time','>=','2018-06-20 23:59:59')
//            ->order('update_time desc')
//            ->buildSql();
//        $data = $db2->table($subQuery."a")
//            ->field("a.loginTel u_phone")
//            ->group('loginTel')
//            ->order('update_time desc')
//            ->select();
//        Db::table('up_z_old_user_note')->insertAll($data);
    }

    //----------------------total_price下面是erp回传问题-------------------------------------------------------------

    public function aaa5()
    {
        set_time_limit(0);
        $db2 = Db::connect('mysql://root:5b5u8419,.@221.231.139.177:3306/new#utf8');
        $status = '已付款,已发货,已排单,已签收';
        $zfstatus = '已付款,已发货,已排单,已签收';
        $exs = '圆通快递,安能快递,申通,申通快递,顺丰,顺丰快递';
//        $subQuery  = $db2->table("app_register_info")
//            ->where('update_time','>=','2018-06-20 23:59:59')
//            ->order('update_time desc')
//            ->buildSql();
//        $data = $db2->table($subQuery."a")
//            ->field("a.loginTel u_phone,concat('用户',a.loginTel) u_name,a.loginPWD u_pass,a.update_time u_time")
//            ->group('loginTel')
//            ->order('update_time desc')
//            ->count();
//        dump($data);die;
//        $page = Db::table('up_z_z')->where('id',1)->value('pages');
//        $field = 'Id order_no,allPrice total_price,expressPrice express_original_price,relName name';
//        $field .= ',relTel mobile,sendAddr address,upZF_time pay_time,zf_last_time send_time';
//        $field .= ',expressName express,expressNum express_no,upTime confirm_time,upZF_time created_at,upZF_time updated_at';
//        $field .= ',car_num all_good_nums,clothPrice all_goods_price,loginTel old_phone';
//        $order = $db2->table('pro_book_info_copy1')
//            ->where('status','in',$status)
//			->where('zf_status','in',$zfstatus)
//			->where('expressName','in',$exs)
////			->where('loginTel','13851664186')
//            ->field($field)
//            ->order('Id ASC')
////            ->page($page,200)
//            ->count();
//        dump($order);die;
//        if(!$order){
//            exit();
//            die;
//        }
//        $field = 'getNum,clothPrice,size,Name,sname,clothCode';
//        foreach ($order as $k => $v){
//            $up = $db2->table('report_order_detail_all_copy')
//                ->where('Id',$v['order_no'])
//                ->field('Name,schoolId,gradeYear')
//                ->find();
////            dump($up);
//            $v['first_good_name'] = $up['Name'];
//            $v['order_school'] = $up['schoolId'];
//            $v['order_erp_year'] = $up['gradeYear'];
//            $order_id = Db::table('up_z_old_order')->insertGetId($v);
//            //----------------------------------------------
//            $detail = $db2->table('report_order_detail_all_copy')
//                ->where('Id',$v['order_no'])
//                ->field($field)
//                ->select();
////            dump($detail);die;
//            foreach ($detail as $k2 => $v2){
//                $de = [ //getNum,clothPrice,size,Name,sname,clothCode,,
//                    'order_id' => $order_id,
//                    'num' => $v2['getNum'],
//                    'unit_price' => $v2['clothPrice'],
//                    'attr_id' => $v2['size'],
//                    'goods_info' => $v2['Name'] . '/' . $v2['size'],
//                    'created_at' => $v['created_at'],
//                    'updated_at' => $v['created_at'],
//                    'detail_express' => $v['express'],
//                    'detail_express_no' => $v['express_no'],
//                    'old_phone' => $v['old_phone'],
//                    'old_stu_name' => $v2['sname'],
//                    'cloth_code' => $v2['clothCode']
//                ];
//                $newgoodcode = Db::table('up_z_new_old_img')->where('old',$v2['clothCode'])->value('new');
//                $goods_id = Db::table('up_goods')->where('good_coding',$newgoodcode)->value('good_id');
//                if(empty($goods_id)){
//                    $goods_id = 0;
//                }
//                $de['goods_id'] = $goods_id;
//                Db::table('up_z_old_order_detail')->insert($de);
//            }
//            Db::table('up_z_z')->where('id',1)->setInc('pages');
//        }
        die;
    }

    /**
     * 售后同意退款之后且打完款之后告诉erp打了多少款
     */
    public function refundMoneyNoticeErp()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $where = [];
        $where['order_master_status'] = 4;
        $where['order_master_push'] = 1;
        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',order_cancel_number,order_cancel_time,order_cancel_remark';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where)
            ->field($field)
            ->select();
//        dump($datas);die;
    }
    // public function zhangG()
    // {
    // $arr = ['AHB004A00','AHB013A00','AHA018A00','AHC009A00','AHC007B00','HBH002A02','JSD004A00','JSD001A00','JSD002A00','JSD003A00','JSL063A00','JSL068A00','JSL060A00','JSL059A00','JSL069A00','JSL061A00','JSL070A00','JSL065A00','JSL066A00','JSL067A00','AHM007A02','AHM007A03','AHK002A00','JSF001A02','JSF001A03','ZJA002A02','ZJA009A00','ZJA003A00','AHA001A00','AHA003A00','AHA004A00','AHA010A02','AHA011A00','HBB001A00','JSH011A00','JSH003A00','AHF002A00','AHD004A02','JSL008A00','JSL062A00','JSA142A00','JSH001A00','JSA137A00','JSM001A00','JSM001A05','JSB001A00','JSH002A00','JSJ006A00','JSM003A00','JSB007A04','JSB007A00','JSB008A00','JSA069A00','JSJ004A00','JSA098A00','JSL001A00','JSL071A00','JSE006A00','SDP001A02','SCR001A02','JSA065A02','JSA065A03','JSA065A04','JSA043A00','JSA046A00','JSA092A00','JSA095A02','JSA178A00','JSA106A02','JSA152A00','JSA053A10','JSA053A11','JSA053A12','JSA053A13','JSA120A00','JSA001A00','JSA004A00','JSA014A00','JSA003A02','JSA003A03','JSA068A00','JSA002A00','JSA006A00','JSA007A00','JSA008A00','JSA009A00','JSN001A02','JSE002A02','JSE002A03','JSE002A04','JSJ011A02','JSJ011A03','JSA154A02','JSA066A00','JSA088A00','JSA119A00','JSA048A00','JSA025A00','JSA026A00','JSA028A00','JSA029A02','JSA030A00','JSA027A00','JSA121A02','JSA121A00','JSA130A00','JSA044A02','JSA044A03','JSA093A00','JSA061A00','JSA122A00','JSA063B00','JSA063C00','JSA062A00','JSA033A00','JSA031A00','JSA109A00','JSA127A00','JSA089A00','JSA052A00','JSA034A03','JSA034B02','JSA039A00','JSA117A00','JSA032A00','JSA131A00','JSA150A00','JSA135A00','JSA140A00','JSA021A00','JSA024A00','JSA023A02','JSA022A00','JSA055A00','JSA103A00','JSA058A02','JSA037A00','JSA145A00','JSA080A00','JSA064A00','JSA156A00','JSA139A00','JSA087A00','JSA134A02','JSA097A00','JSA132A00','JSA126A00','JSA112A00','JSA111A00','JSA083A00','JSA054A00','JSA054B00','JSA056A02','JSA056A03','JSA057A00','JSA078A00','JSA128A02','JSA107A00','JSA019A00','JSA019A03','JSA019A99','JSA018A00','JSA016A02','JSA016A03','JSA016A04','JSA050A00','JSA038A02','JSA040A00','JSA124A00','JSM012A00','JSA110A00','SJJ001A02','SJJ001A03','ZJD002A00','ZJJ001A02','ZJJ001A03','JSM007A00','JSM002A00','JSM006A00','JSM004A00','HBB003A00','HBB002A00','JSB011A00','JSB006A00','JSB006A04','JSB004A00','JSB012B00','JSB012C00','JSB003A00','JSB003A05','JSB002A00','JSB005A00','AHB001A03','JSJ005A02','ZJA010A00','ZJA001A00','JSN002A00','JSC001A00','JSC007A00','JSN006A00','JSC002A00','JSC005A00','JSC006A00','JSJ003A02','JSJ003A03','JSK001A00','ZJA008A00','JSL004A02','JSL004A03','JSL007A00','JSL022A02','JSL013A02','JSL021A00','JSL040A02','JSL003A00','JSL017A00','JSL005A00','JSL010A02','JSL030A00','JSL002A00','JSL020A00','JSA108A02','SJJ002A02'];

    // $goods_id = Db::table('up_school_good')->where('sg_school_erp','in',$arr)->where('sg_year',2017)->setField('sg_status',2);
    // echo $goods_id;
    // }
    /**
     * 未发货之前取消订单的，发给erp
     */
    public function cancelOrderErpPushNoSend()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        //2、售后的推不管退还是换，先推个售后
        $where2 = [];
        $where2['tui_type'] = 2;
        $where2['type'] = 1;
        $where2['status'] = 2;
        $where2['erp_push'] = 2;
        $where2['t.is_send'] = 0;
        $where2['t.tui_erp_push_no_get'] = 1;

        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,o.name,o.mobile,o.address,o.order_address2,o.order_back_order_id';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',t.type,t.order_erp_wl_no';
        $field .= ',t.erp_year,t.erp_done,t.express,t.express_no,t.remark,t.created_at,new_erp_have';

        $datas = Db::table('up_self_order_tui')->alias('t')
            ->join('up_self_order o', 't.order_id=o.order_id', 'LEFT')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where2)
            ->where('order_erp_wl_no','in','app16215087568242709,app162148554286241702,app162083159484313496,app162124917182312877,app1621260643124318,app162124900144279379')
            ->field($field)
            ->group('order_erp_wl_no')
            ->select();
        //dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                //A:先推退货
                $youhua_status = false;

                //B:换货的再推增补单
                if ($v['type'] == 1) {
                    $master = [
                        'cAppOrderNo' => $v['order_erp_wl_no'],
                        'iBusiness' => 2, //1 是增补，2是换货的增补
                        'dOrderMoney' => $v['all_goods_price'],
                        'dFreight' => $v['express_original_price'],
                        'cReceiveName' => $v['name'],
                        'cReceiveMobile' => $v['mobile'],
                        'cReceiveAddress' => $v['order_address2'],
//                            'STU_NAME' => $v['uson_username'],
//                            'STU_ID' => $v['uson_idcard'],
//                            'STU_PHONE' => $v['uson_parent_phone'],
                        'cStuSchool' => $v['school_erp'],
                        'cStuGrade' => $v['uson_grade'],
                        'cStuClass' => $v['uson_class'],
                        'iYears' => $v['erp_year'],
//                            'PREDATE' => $v['erp_done'],
                        'cSerialNum' => $v['order_back_order_id'],
                        'cOldOrderCode' => $v['order_no'],
                        'cDate' => $today,
                        'cRemark' => '',
                    ];
                    $field = 'erp_huan_uninumber cUniqueNumber,good_coding cProCode,erp_new_size cProSize,unit_price dPrice,refund_num dQty,s.user_gender iSex';
                    $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                    $details = Db::table('up_self_order_tui')->alias('t')
                        ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                        ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                        ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                        ->where($where2)
                        ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                        ->field($field)
                        ->select();
                    $body = [
                        'Head' => $master,
                        'Rows' => $details,
                        'Tradeid' => $v['order_erp_wl_no'] . $v['order_id']
                    ];
                    $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderSync";
                    $result = $this->curl_erp($url, json_encode($body));
                    if (isset($result['errcode']) && $result['errcode'] == 0) {
                        Db::table('up_self_order_tui')
                            ->where($where2)
                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                            ->setField('tui_erp_push_no_get', 2);
                    }else{
                        dump($result);
                    }
                }
            }
        }
    }
	public function mwwtest()
	{
//        $sure = $this->kkkkk(594, 2022, 1, 1, 'FNAJ4D010301');
//        dump($sure);
		// exit();
//        $update = [
//            'is_pay' => 1,
//            'order_no' => '202208261155094232467',
//            'order_back_order_id' => '4200001632202208265573702827',
//            'order_query_id' => '',
//            'pay_time' => '2021-08-26 11:55:35',
//        ];
//        $res = Db::table('up_self_order')->where('order_id','510327')->update($update);
//        dump($res);
//        die;
		// $today = date('Y-m-d H:i:s');;
        // $APP_DOCNO = '202105120817175255631';
        // $COMNAME = '顺丰';
        // $FASTNO = 'SF1329850755997';
        // $order = Db::table('up_self_order')->where('order_no', $APP_DOCNO)->field('order_id,is_send')->find();
        // $res1 = Db::table('up_self_order')
            // ->where('order_no', $APP_DOCNO)
            // ->update([
                // 'is_send' => 1,
                // 'send_time' => $today,
                // 'updated_at' => $today,
                // 'express' => $COMNAME,
                // 'express_no' => $FASTNO,
            // ]);
        // $res2 = Db::table('up_self_order_detail')
            // ->where('order_id', $order['order_id'])
            // ->update([
                // 'updated_at' => $today,
                // 'detail_express' => $COMNAME,
                // 'detail_express_no' => $FASTNO,
            // ]);
        // $APP_DOCNO = '202105051912556228984';
        // $COMNAME = '顺丰';
        // $FASTNO = 'SF1333632001323';
        // $order = Db::table('up_self_order')->where('order_no', $APP_DOCNO)->field('order_id,is_send')->find();
        // $res3 = Db::table('up_self_order')
            // ->where('order_no', $APP_DOCNO)
            // ->update([
                // 'is_send' => 1,
                // 'send_time' => $today,
                // 'updated_at' => $today,
                // 'express' => $COMNAME,
                // 'express_no' => $FASTNO,
            // ]);
        // $res4 = Db::table('up_self_order_detail')
            // ->where('order_id', $order['order_id'])
            // ->update([
                // 'updated_at' => $today,
                // 'detail_express' => $COMNAME,
                // 'detail_express_no' => $FASTNO,
            // ]);
			// dump($res1);
			// dump($res2);
			// dump($res3);
			// dump($res4);
	}
    protected function  kkkkk($school_id,$year,$sex,$type='',$less_code='',$getyear=''){
        extract(input());
        $school = Db::table('up_school')
            ->where('school_id',$school_id)
            ->field('school_history,school_erp,school_status,school_no_years')
            ->find();
        //1、学校要是下架了，则看不到所有的商品
        if(empty($type)){
            $codes = array();
            if($school['school_status'] != 1){
                return $codes;
            }
        }
        //2、如果学校禁止了某些年份，则不展示这些年份的
        //3、只展示符合性别的
        $codewhere = [
            'sg_sex' => ['in',"$sex,3"],
        ];
        $codewhere2 = [
            'sg_school_erp' => $school['school_erp'],
        ];
        if($school['school_no_years']){
            $codewhere['sg_year'] = ['not in',$school['school_no_years']];
        }
        //现在的逻辑是，一定是只有这一年的，不是当年的也会只找当年的(但是购物车就比较特殊了，要看到所有之前选择的)
        if($getyear === 2){ //购物车来的
            if($school['school_history'] == 1){
                $codewhere2['sg_year'] = $year;
            }
        }else{
            $codewhere2['sg_year'] = $year;
        }

        if($type){
            //如果存在Q版，则确认下这个Q版在不在这个用户所在学校里的当年的，如果不在，返回正常，如果在，返回Q
            //肯定有值，因为列表就是从这个条件里出去的
            if($type == 2){ //商品里这个尺码是有Q版的，但是销售数据里不一定有
                $paixu = 'DESC';
                //这种情况比较特殊，如果我那一年没有Q版，下一年有了Q款，恰好后台又全放开了这所学校，则先查下当年有没有Q版，没有的话也是ASC
                $nowhave = Db::table('up_school_good')
                    ->where($codewhere)
                    ->where($codewhere2)
//                        ->where('sg_year',$year)
                    ->where('sg_good_coding_less',$less_code)
                    ->where('sg_status',1)
                    ->where("sg_good_q",2)
                    ->find();
                if(empty($nowhave)){
                    $paixu = 'ASC';
                }
            }else{ //商品里这个尺码是没有Q版的，但是有可能这个款号有Q版，所有正序排一定给的是正常的
                $paixu = 'ASC';
            }
dump($codewhere);
dump($codewhere2);
            $codes = Db::table('up_school_good')
                ->where($codewhere)
                ->where($codewhere2)
                ->where('sg_good_coding_less',$less_code)
                ->where('sg_status',1)
                ->order("sg_good_q $paixu")
                ->find();
        }else{
            $codewhere['sg_good_q'] = 1;
            $codewhere['sg_status'] = 1;
            $codes = Db::table('up_school_good')
                ->where($codewhere)
                ->where($codewhere2)
                ->column('sg_good_coding');
            //这个unset放开就可以展示多年份了
            //unset($codewhere2['sg_year']);
            $years = Db::table('up_school_good')
                ->where($codewhere)
                ->where($codewhere2)
                ->group('sg_year')
                ->column('sg_year');
            if($getyear === 1){
                return ['codes' => $codes , 'years' => $years];
            }
        }
        return $codes;
    }
    /**
     * 增补订单推送给erp，比较着急的
     */
    public function forZengbuPush()
    {

        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $hours = Db::table('up_about')->where('id', 9)->value('content');
//        $hours = (int)$hours;
        $hours_ago = date("Y-m-d H:i:s", ($time - 3600 * $hours));
        $where['is_pay'] = 1;
        $where['order_contract'] = 2;
        $where['o.is_delete'] = 0;
        $where['o.is_send'] = 0;
        $where['o.order_push_erp'] = 1;
        $where['o.order_cancel_status'] = ['<=', 2];
        $where['o.order_no'] = ['in', '202311151125224243625'];
        $field = 'o.order_no,o.order_id,o.name,o.mobile,o.address,o.order_address2,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',o.order_erp_year,o.order_erp_done,o.order_back_order_id,o.created_at,o.remark,o.pay_type';
        $ids = '15923920265889501,15923965045850273,15923967655731051';
        $ids .= ',15923967957642564,15923968251398936';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($where)
            ->field($field)
            ->page(1,10)
            ->select();
//        dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['order_no'],
//                    'iSaleType' => 2, //1统购  2增补
                    'iBusiness' => 1, //1 是增补，2是换货的增补
                    'dOrderMoney' => $v['all_goods_price'],
                    'dFreight' => $v['express_original_price'],
                    'cReceiveName' => $v['name'],
                    'cReceiveMobile' => $v['mobile'],
                    'cReceiveAddress' => $v['order_address2'],
//                    'cStuName' => $v['uson_username'] ?: '',
//                    'cStuID' => $v['uson_idcard'] ?: '',
//                    'cStuMobile' => $v['uson_parent_phone'] ?: '',
                    'cStuSchool' => $v['school_erp'] ?: '',
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cHPreDate' => $v['order_erp_done'] ? date('Y-m-d',strtotime($v['order_erp_done'])) : '',
                    'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                    'cStuGrade' => $v['uson_grade'] ?: '',
                    'cStuClass' => $v['uson_class'] ?: '',
                    'iYears' => $v['order_erp_year'],
//                    'cPreDate' => $v['order_erp_done'],
                    'cSerialNum' => $v['order_back_order_id'],
                    'Oldordercode' => '',
                    'cRemark' => $v['remark'],
                    'cDate' => substr($v['created_at'], 0, 10)
                ];
                $field = 'goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,unit_price dPrice,num dQty,s.user_gender iSex';
                $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field($field)
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_no'] . $v['order_id']
                ];
                $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    $res = Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->update(['order_push_erp' => 2,'new_erp_have' => 2]);
                    dump($res);
                }else{
                    dump($result);
                }
            }
        }
    }
    //-----------------------下面的这两个是有用的-------------------------------
    public function autoCancelZengbu()
    {
        set_time_limit(0);
        $data = Db::table('up_self_order')
            ->where('auto_cancel', 2)
            ->where('order_cancel_status', 4)
            ->field('order_no,order_id,total_price,pay_type,user_id,is_pay,order_contract,is_send,order_cancel_status,order_push_erp,pay_time')
            ->page(1,2)
            ->select();
//        dump($data);die;
        if($data){
            $today = date('Y-m-d H:i:s');
            foreach ($data as $k => $order){
                $order_id = $order['order_id'];
                $cantui = false;
                if($order['order_push_erp'] == 1){
                    $cantui = true;
                }else{
                    $body = [
                        'SaleOrderNo' => $order['order_no'],
                        'OrdType' => 0
                    ];
                    $url = config('erpoms')['erpurl'] . "/Api/App/SaleOrderCancel";
                    $result = $this->curl_erp($url, json_encode($body));
                    if (isset($result['errcode']) && $result['errcode'] == 0) {
                        $cantui = true;
                    }else{
                        $update = [
                            'order_cancel_status' => 2,
                            'auto_cancel' => 4, //4代表出错了，联系客服
                            'updated_at'=>$today,
                        ];
                        if (isset($result['errcode']) && $result['errcode'] == 99) {
                            $update['auto_cancel'] = 3; //3代表出库了，不能取消
                        }
                        //记录下错误的情况下返回了什么
                        Db::table('up_zz_error_order')->insert([
                            'orderno' => $order_id,
                            'backno' => 'U8那边取消订单失败了',
                            'special_u' => json_encode($result),
                            'time' => $today
                        ]);
                    }
                }
                if($cantui == true){
                    $update  = [
                        'order_cancel_status'=>3,
                        'order_cancel_pay'=>3,
                        'order_master_status'=>4,
                        'is_pay'=>2,
                        'order_cancel_money'=>$order['total_price'],
                        'auto_cancel'=>3,
                        'order_cancel_number' => 'T' . time() . rand(1000000,9999999),
                        'updated_at'=>date('Y-m-d H:i:s',time()),
                    ];
                    if($order['order_push_erp'] != 1) $update['order_cancel_push_erp'] = 2;
                    $payInfo = [
                        'total_price' => $order['total_price'],
                        'money' => $order['total_price'],
                        'number' => $order['order_no']
                    ];
                    $refundNo = $update['order_cancel_number'];
                    if($order['pay_type'] == 1){ //微信
                        $tuiwx = new \app\api\controller\Tuiwx();
                        $res = $tuiwx->refundWx($payInfo,$refundNo);
                    }elseif ($order['pay_type'] == 2){ //支付宝
                        $tuiali = new \app\api\controller\Ali();
                        $res = $tuiali->refund($payInfo,$refundNo);
                    }else{
                        //支付方式有问题？不会出现这个情况
                        $update = [
                            'order_cancel_status' => 2,
                            'auto_cancel' => 4, //4代表出错了，联系客服
                            'updated_at'=>$today,
                        ];
                    }
                    //退款失败，小概率，联系客服
                    if($res['status'] != 200) {
                        $update = [
                            'order_cancel_status' => 2,
                            'auto_cancel' => 5, //退款失败
                            'updated_at'=>$today,
                        ];
                    };
                }
                $res = Db::table('up_self_order')->where('order_id',$order_id)
                    ->update($update);
                if($res){
                    if($cantui == true && $update['order_cancel_status'] == 3) {
                        allInRevenue(2,$order['total_price'],$order['user_id'],4,$order_id,0,$order_id);
                    }
                }else{
                    //记录下，没改成功
                    Db::table('up_zz_error_order')->insert([
                        'orderno' => $order_id,
                        'backno' => '取消订单改数据库失败了',
                        'time' => $today
                    ]);
                }
            }
        }
        exit();
    }
    public function closeSaleOrder(){
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $days = Db::table('up_about')->where('id', 19)->value('content');
        $days = (int)$days;
        $days_ago = date("Y-m-d H:i:s", ($time - 3600 * 24 * $days));
        $where2 = [];
        $where2['tui_type'] = ['in','1,2'];
        $where2['status'] = 2;
        $where2['erp_push'] = 1;
        $where2['express_no'] = '';
        $where2['status_time'] = ['<=',$days_ago];
        $where2['created_at'] = ['>=','2023-06-02 10:00:00'];
        $datas = Db::table('up_self_order_tui')
            ->where($where2)
            ->group('order_erp_wl_no')
            ->field('order_erp_wl_no,order_id')
            ->select();
//        dump($datas);die;
        if($datas){
            foreach ($datas as $k => $v){
                //多了一个关闭的状态
                Db::table('up_self_order_tui')
                    ->where('order_erp_wl_no',$v['order_erp_wl_no'])
                    ->update([
                        'status' => 4
                    ]);
                try{
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->setField('tui_status',1);
                }catch(\Exception $e){}
            }
        }
        exit();
    }
}